﻿using System;
using Microsoft.Xna.Framework;

namespace SolarWinds.Extensions
{
    public static class BoundingBoxExtension
    {
        public static BoundingBox Transform(this BoundingBox boundingBox, Matrix matrix)
        {
            Vector3 min = Vector3.Transform(boundingBox.Min, matrix);
            Vector3 max = Vector3.Transform(boundingBox.Max, matrix);
   
            return new BoundingBox(min, max);
        }

        public static BoundingBox CreateAxisAligned(this BoundingBox boundingBox, Matrix matrix)
        {
            BoundingBox aabb;

            Vector3[] corners = boundingBox.GetCorners();

            Vector3.Transform(corners, ref matrix, corners);

            aabb.Min.X = aabb.Max.X = corners[0].X;
            aabb.Min.Y = aabb.Max.Y = corners[0].Y;
            aabb.Min.Z = aabb.Max.Z = corners[0].Z;

            for (int i = 1; i < BoundingBox.CornerCount; ++i)
            {
                if (corners[i].X < aabb.Min.X) aabb.Min.X = corners[i].X;
                if (corners[i].X > aabb.Max.X) aabb.Max.X = corners[i].X;

                if (corners[i].Y < aabb.Min.Y) aabb.Min.Y = corners[i].Y;
                if (corners[i].Y > aabb.Max.Y) aabb.Max.Y = corners[i].Y;

                if (corners[i].Z < aabb.Min.Z) aabb.Min.Z = corners[i].Z;
                if (corners[i].Z > aabb.Max.Z) aabb.Max.Z = corners[i].Z;
            }

            return aabb;
        }
    }
}
